﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;

public class RedisHelper
{
    private readonly ConnectionMultiplexer _redis;

    private IDatabase _database;
    public RedisHelper(string redisConnectionString)
    {
        _redis = ConnectionMultiplexer.Connect(redisConnectionString);
        if (_database == null)
        {
            _database = _redis.GetDatabase();
        }
    }

    public void SetValue(string key, string value)
    {
        _database.StringSet(key, value);
    }

    public string GetValue(string key)
    {
        return _database.StringGet(key);
    }

    public void ListLeftPush(string Key, string Val)
    {
        _database.ListLeftPush(Key, Val);
    }

    public List<RedisValue> ListRange(string Key)
    {
        return _database.ListRange(Key, 0, -1).ToList();
    }

    public void HashSet(string Key, string Field, string value)
    {
        _database.HashSet(Key, Field, value);
    }

    public Dictionary<T, K> HashGetAll<T, K>(string Key)
    {
        var result = new Dictionary<T, K>();
        var all = _database.HashGetAll(Key);

        foreach (var entry in all)
        {
            T field = (T)Convert.ChangeType(entry.Name, typeof(T));
            K value = (K)Convert.ChangeType(entry.Value, typeof(K));
            result[field] = value;
        }
        return result;
    }

    public string HGet(string Key, string Field)
    {
        return _database.HashGet(Key, Field);
    }
}
